﻿using System;
using System.Windows.Forms;
using POS.BusinessComponents;
using POS.BusinessEntities;

namespace POS.UI.Mantenimientos
{
    public partial class BusquedaForm : Form, IBusquedaForm
    {
        #region Declarations

        private readonly TipoEntidad entidad;
        private readonly string filtro;

        private const int columnaId = 0;
        private const int columnaNombre = 1;

        #endregion

        #region Properties: Public

        public int SelectedId { get; set; }
        public string SelectedCode { get; set; }
        public string SelectedName { get; set; }
        
        #endregion

        #region Constructors

        private BusquedaForm()
        {
            InitializeComponent();
        }

        public BusquedaForm(TipoEntidad entidad, string filtro)
            : this()
        {
            this.entidad = entidad;
            this.filtro = filtro;
        }

        #endregion

        #region Event Handlers

        private void BusquedaForm_Load(object sender, EventArgs e)
        {
            filtroTextBox.Text = filtro;
            Text += entidad;

            buscarButton.PerformClick();

            dataGrid.Columns[columnaId].Visible = false;
            dataGrid.Columns[columnaNombre].Width = 100;
            dataGrid.Columns[columnaNombre].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }

        private void AceptarButton_Click(object sender, EventArgs e)
        {
            if (dataGrid.SelectedRows.Count == 1)
            {
                SelectedId = (int)dataGrid.SelectedRows[0].Cells[columnaId].Value;
                SelectedName = dataGrid.SelectedRows[0].Cells[columnaNombre].Value.ToString(); 
                Close();
            }
        }

        private void dataGrid_KeyPress(object sender, KeyPressEventArgs e)
        {
            AceptarButton.PerformClick();
        }

        private void dataGrid_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            AceptarButton.PerformClick();
        }

        private void buscarButton_Click(object sender, EventArgs e)
        {
            var results = new BCEntidad(entidad).GetList(filtroTextBox.Text.Trim());
            dataGrid.DataSource = results;
            dataGrid.Focus();
        }

        private void filtroTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
                buscarButton.PerformClick();
        }
        #endregion
        
    }
}
